package com.schooleducation.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.schooleducation.entity.LessonSubscribe;
import com.schooleducation.entity.User;
import com.schooleducation.service.ServiceFactory;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/userLesson")
public class UserLessonController {

	@Resource(name = "serviceFac")
	private ServiceFactory serviceFac;
	
	/**
	 * 获取用户订阅可界面
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String getUserInfoPage(HttpSession session, Model model) {
		User user = (User) session.getAttribute("user");
		if (user != null) {
			List<LessonSubscribe> lessons = serviceFac.getLessonService().getSubscribeLesson(user, 0);
			
			model.addAttribute("user", user);
			model.addAttribute("lessonList", lessons);
			
			return "userLesson";
		} else {
			return "redirect:login";
		}
	}
	
	/**
	 * 取消课程订阅数据提交
	 * @param session
	 * @param subscribeId
	 * @return
	 */
	@RequestMapping(value="delSubscribe", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String deleteSubscribeLesson(HttpSession session,int subscribeId) {
		User user = (User) session.getAttribute("user");
		Map<String, Object> state = new HashMap<String, Object>();
		if (user != null) {
			state.put("isLogin", "yes");
			if(serviceFac.getLessonService().deleteSubscribeLesson(subscribeId)) {
				state.put("del", "success");
			} else {
				state.put("del", "fail");
			}
		} else {
			state.put("isLogin", "no");
		}
		return JSONObject.fromObject(state).toString();
	}
}